﻿using Microsoft.AspNetCore.Mvc;
using MVC高级教程.Models;
using System.Web;

namespace MVC高级教程.Controllers
{
    /// <summary>
    /// Http请求测试
    /// </summary>
    public class 请求测试Controller : Controller
    {
        public IActionResult Search()
        {
            var studentName = Request.Query["studentName"];

            List<Student1> list = new()
            {
                new(1,"余冰",32),
                new(2,"老赵",34),
                new(3,"老刘",35)
            };

            if (!string.IsNullOrWhiteSpace(studentName))
            {
                //Linq模糊查询
                list = list.Where(p=>p.Name.Contains(studentName)).ToList();
            }
            //响应体
            return View(list);
        }

        [HttpGet]
        /// <summary>
        /// 使用Ajax请求
        /// </summary>
        /// <returns></returns>
        public IActionResult Search1()
        {
            List<Student1> list = new()
            {
                new(1,"余冰",32),
                new(2,"老赵",34),
                new(3,"老刘",35)
            };
            //获取请求头
            string myTokens = Request.Headers["mytoken"].ToString();//此处获取请求头中的某一个条目

            //Url解码
            myTokens = HttpUtility.UrlDecode(myTokens);

            if (!string.IsNullOrWhiteSpace(myTokens))
            {
                //Linq模糊查询
                list = list.Where(p => p.Name.Contains(myTokens)).ToList();
            }

            //响应体
            return View(list);
        }


        /// <summary>
        /// Ajax方式get请求测试
        /// </summary>
        /// <returns></returns>
        public IActionResult getAjax()
        {
            List<Student1> list = new()
            {
                new(1,"余冰",32),
                new(2,"老赵",34),
                new(3,"老刘",35)
            };
            //获取请求头
            string myTokens = Request.Headers["mytoken"].ToString();//此处获取请求头中的某一个条目

            myTokens = HttpUtility.UrlDecode(myTokens);

            if (!string.IsNullOrWhiteSpace(myTokens))
            {
                //Linq模糊查询
                list = list.Where(p => p.Name.Contains(myTokens)).ToList();
            }

            return Ok(list);
        }



        /// <summary>
        /// 测试响应体
        /// </summary>
        /// <returns></returns>
        public IActionResult ResponseTest()
        {
            Response.Headers["Content-Type"] = "text/plain;charset=utf8";
            //Response.ContentType = "text/plain;charset=utf8";//通过设置响应内容类型，约定往响应体中输出的内容类型
            Response.WriteAsync("你好呀，测试响应体");//异步的往响应体中写东西(直接写回乱码的)

            //先返回一个空结果
            return new EmptyResult(); 
        }
    }
}
